<template>
    <div id="baseInfo-container" class="container">
        <div class="content">

            <div v-show="groupName.length > 0" class="groupTitle">
                <div class="name">* {{groupName}}</div>
<!--                <div class="operation" v-show="currentEditSectionIndex === -1">-->
<!--                    <el-button v-show="maxSectionCount>allFieldList.length && groupId !== '10100' && total>0" type="primary" size="mini" round plain @click="addSection">新增</el-button>-->
<!--                    <el-button v-show="groupId !== '10500' && groupId !== '10100' && groupId !== '12500'" type="primary" size="mini" round plain @click="dialogVisible_import=true">导入</el-button>-->
<!--                    <el-button v-show="total > 0" type="primary" size="mini" round plain @click="exportData" style="margin-left: 10px;">导出</el-button>-->
<!--                </div>-->
            </div>

            <div class="section" v-for="(paramList,index) in allFieldList" :key='index'>
                <base-info-view :isReviewAvatar=false :paramList="currentEditSectionIndex===index?[]:paramList" :groupId="groupId"></base-info-view>
                <basic-info-edit :paramList="currentEditSectionIndex===index?JSON.parse(JSON.stringify(paramList)):[]" :groupId="groupId" @cancelEdit='cancelEdit' @editFinish="editFinish"></basic-info-edit>

                <!-- 侧边操作按钮 -->
<!--                <div v-show="total>0" class="operationButton">-->
<!--                    <el-button v-show="currentEditSectionIndex===-1" native-type="button" type="primary" icon="el-icon-edit" size="mini" circle plain @click="currentEditSectionIndex=index"></el-button>-->
<!--                    <el-button v-show="(currentEditSectionIndex === index || currentEditSectionIndex === -1) && groupId !== '10100'?true:false"  native-type="button" type="danger" icon="el-icon-delete" size="mini" circle plain @click="deleteSection(paramList,$event)"></el-button>-->
<!--                </div>-->

                <!-- 底线 -->
                <div v-show="totalPages > 1 || index !== (total-1)" class="bottomLine"></div>

                <!-- 开始填写提醒 -->
                <div v-show="total<=0 && currentEditSectionIndex=== -1" class="editPrompt">
                    <p style="font-size: 18px">无</p>
<!--                    <el-button type="primary" size="mini" round plain @click="currentEditSectionIndex=index" style="margin-left: 10px;">-->
<!--                        <i class="el-icon-edit"></i>&nbsp;开始录入-->
<!--                    </el-button>-->
                </div>
            </div>

            <el-pagination
                v-show="totalPages > 1 && currentEditSectionIndex===-1"
                background
                layout="total,prev, pager, next"
                @current-change="loadBaseAllField()"
                :current-page.sync="currentPage"
                :page-size="pageSize"
                :total="total">
            </el-pagination>

        </div>

        <basic-info-nav ref="basicInfoNavigation" class="rightSideTab" :defaultGroupId="groupId" @groupClick="groupClick"></basic-info-nav>


        <!-- 弹框：导入数据弹框 -->
        <el-dialog title="" :visible.sync="dialogVisible_import" width="20%">
            <div class="dialogVisible_import_content">
                <div class="download">
                    <el-button type="primary" size="mini" round @click="exportModel">下载模板</el-button>
                    <div>（若已下载，可直接略过）</div>
                </div>
                <div class="import">
                    <el-button type="primary" size="mini" :loading="dialogVisible_import_button_status" round @click="$event.currentTarget.nextSibling.click();">

                        <span v-show="dialogVisible_import_button_status === true">正在解析...</span>
                        <span v-show="dialogVisible_import_button_status === false">导入表格</span>
                    </el-button>
                    <input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" @change="importData($event)" style="display:none;">
                    <div>（必须以模板形式导入）</div>
                </div>
            </div>
        </el-dialog>

        <!-- 弹框：导入数据编辑、保存 -->
        <base-info-import :data="dialogVisible_import_data" :groupId="groupId" :groupName="groupName"></base-info-import>

    </div>
</template>
<script>

import { infoEntryUploadImagePost,baseInfoGroupDataPost,infoEntryEnteredDataPost,infoEntryEnteredExportModelGet,infoEntryEnteredImportPost,infoEntryEnteredSavePost,infoEntryQaCategoriesPost,infoEntryCategoryTypePost,infoEntryGoupFieldPost,infoEntryUploadFilePost,infoEntryCommitPost} from '@/service/api'
import { processingGroupData,getParamKey,makeParamKey,exportData,exportModel,
    processingParamValueByType,deleteSection,processingAssociatedFields,handleGetTimeData } from '../../service/personalInfoDataProcessing'
import BasicInfoNav from "@/components/BasicInfo/BasicInfoNav";

export default {
    data(){
        return {
            allFieldList:[],
            groupId:"",            // 当前级ID
            groupName:"",          // 当前组名称
            groupType:"1",         // '1'为一级表，'2'为二级表
            maxSectionCount:0,
            currentEditSectionIndex:-1, // 当前正在编辑的section数据索引

            // 提交按钮loading
            commitButtonIsLoading:false,

            // 二级弹框 - 导入
            dialogVisible_import:false,
            dialogVisible_import_data:[], // 导入的数据
            dialogVisible_import_button_status:false, // 导入按钮状态，true正在导入，false为导入完成


            currentPage: 1,
            pageSize: 5,
            total:0,       // 总数
            totalPages:0,  // 总页数

            currentAddSectionIndex:-1, // 当前正在添加的seciont索引
        }
    },
    components:{
        BasicInfoNav,
    },
    mounted(){

        var that = this;
        window.addEventListener("message", function(event) {

            // 二级表保存完成回调
            if (event.source == window && event.data.source) {

                switch(event.data.source){

                    case "review-base-info-secondary-save-callback":{  // 二级表保存回调

                        //  有二级表的一级表必须只能有一条，否则如下逻辑将报错
                        event.data.data.forEach(function (field) {
                            let paramList = that.allFieldList[0];
                            for(let i=0;i<paramList.length;i++){
                                if(paramList[i].id === field.id){
                                    if(paramList[i].userSelection.parameterValue !== field.attr1){

                                        // 切换一级表为编模式
                                        if(that.currentEditSectionIndex === -1){
                                            that.currentEditSectionIndex = 0;
                                        }
                                    }

                                    // 修改参数值，并模拟触发字段onchange事件
                                    window.postMessage({
                                        source:"review-basic-info-form-value-change-event",
                                        data:{
                                            value:field.attr1,
                                            paramId:paramList[i].id
                                        }
                                    }, "*");

                                }
                            }
                        })

                        break;
                    }
                    case "review-basic-infomation-entry-fefresh-data":{ // 刷新数据
                        // 刷新当前数据页面
                        that.loadBaseAllField();
                        break;
                    }
                }
            }

        });
    },
    methods:{
        // 导航栏 - 点击组
        groupClick(group){

            if(this.currentEditSectionIndex !== -1){
                this.unsavedPrompt();
                this.$refs.basicInfoNavigation.activeId = this.groupId;
                return;
            }

            this.groupId = group.id;
            this.groupName = group.name;
            this.maxSectionCount = group.attr1;

            this.currentPage = 1;
            this.loadBaseAllField();
        },
        // 未保存提示
        unsavedPrompt(){
            this.$alert('您有信息尚未保存，请先保存一下吧！', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                }
            });
        },
        // 添加section
        addSection(){

            let paramList = JSON.parse(JSON.stringify(this.allFieldList[this.allFieldList.length - 1]));
            paramList.forEach((param)=>{
                // param.maxOrder = param.maxOrder;
                param.userSelection.parameterValue = "";
                param.userSelection.startDate = "";
                param.userSelection.endDate = "";
                param.userSelection.orders = parseInt(param.maxOrder) + 1;
            });

            // 处理关联字段
            for(let i=0;i<paramList.length;i++){
                processingAssociatedFields(paramList[i],paramList);
            }

            this.allFieldList.push(paramList);
            this.currentAddSectionIndex = this.allFieldList.length-1;
            this.currentEditSectionIndex = this.currentAddSectionIndex;

            // 滚动页面至底部
            setTimeout(function(){
                let ele = document.querySelector("#baseInfo-container").parentElement;
                ele.scrollTo(0,ele.scrollHeight);
            }, 100);
        },
        // 删除section
        deleteSection(paramList,$event){

            $event.target.blur();

            var that = this;

            this.$confirm('确定要删除此条数据吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                deleteSection(paramList,that,(isSuccess)=>{
                    // 刷新当前数据页面
                    that.currentPage = 1;
                    that.loadBaseAllField();
                });

            }).catch(() => {
            });
        },
        // 保存完成secion
        editFinish(groupInfo){

            this.currentAddSectionIndex = -1;

            // 刷新当前数据页面
            this.loadBaseAllField();
        },
        // 取消保存
        cancelEdit(){

            // 删除正在添加的secion
            if(this.currentAddSectionIndex > -1){
                this.allFieldList.splice(this.currentAddSectionIndex,1);
                this.currentAddSectionIndex = -1;
            }

            this.currentEditSectionIndex=-1;
        },
        // 加载数据
        loadBaseAllField(){

            var formData = new FormData;
            formData.append("pageNum",this.currentPage);
            formData.append("pageSize",this.pageSize);
            formData.append("groupId",this.groupId);
            formData.append("type",this.groupType);  // '1' 一级表,  ’2’ 二级表
            formData.append("userId",this.$route.query.userId);
            baseInfoGroupDataPost(formData).then(res => {
                console.time("loadTime");
                if(res.code == 200){

                    // 重置编辑状态
                    this.currentEditSectionIndex = -1;

                    var result = processingGroupData(res.data.resultPage.content);
                    this.allFieldList = result.allFieldList; // 所有数据字段

                    this.total = res.data.resultPage.total;
                    this.totalPages = res.data.resultPage.totalPages;

                    // 滚动至页面顶部
                    document.querySelector("#baseInfo-container").parentElement.scrollTop = 0;
                }
                // 加载职称分类option数据列表
                // this.findQaCategories();
                console.timeEnd("loadTime");
            });
        },
        // 导出模板
        exportModel(){
            exportModel(this.groupId,this.groupName,this);
        },
        // 导出数据
        exportData(){
            exportData(this.groupId,this.groupName,this);
        },
        // 导入数据
        importData(event){

            var that = this;
            that.dialogVisible_import_button_status = true;

            var formData = new FormData;
            formData.append("multipartFile",event.target.files[0]);
            formData.append("modelName",this.groupName);

            infoEntryEnteredImportPost(formData).then(res => {
                if(res.code == 200){

                    this.dialogVisible_import = false;

                    let maxOrder = 0;
                    let dataModel = JSON.parse(JSON.stringify(this.allFieldList[0]));
                    dataModel.forEach((param)=>{
                        param.userSelection.parameterValue = "";
                        param.userSelection.startDate = "";
                        param.userSelection.endDate = "";

                        let mo = parseInt(param.maxOrder);
                        if(isNaN(mo) === false){
                            maxOrder =  mo;
                        }
                    });

                    let data = [];
                    // 遍历返回参数
                    for(let i=0;i<res.data.length;i++){
                        ++maxOrder;

                        let paramList = [];
                        let paramListModel = JSON.parse(JSON.stringify(dataModel));
                        for(let pIndex=0;pIndex < paramListModel.length;pIndex++){
                            let paramModel = paramListModel[pIndex];

                            // 从返回数据中寻找对应的参数
                            for(let pIndex=0;pIndex<res.data[i].length;pIndex++){
                                let param = res.data[i][pIndex];

                                if(param.parameterId === paramModel.id){
                                    paramModel.userSelection.parameterValue = param.parameterValue;
                                    paramModel.userSelection.orders = maxOrder;
                                    paramModel.maxOrder = maxOrder;

                                    // 处理整数，以防止用户在excel中编辑时，将小数当作整数保存
                                    if(paramModel.typeValidate === "integer"){
                                        let v = parseInt(paramModel.userSelection.parameterValue);
                                        if(isNaN(v) === false){
                                            paramModel.userSelection.parameterValue = (v + "");
                                        }
                                    }

                                    // 屏蔽附件、照片等文件的值
                                    if(paramModel.type === "file" || paramModel.type === "img"){
                                        paramModel.userSelection.parameterValue = "";
                                    }

                                    // 有二级表的字段，其值全部置为0
                                    if(paramModel.isLevel === '2'){
                                        paramModel.userSelection.parameterValue = 0;
                                    }

                                    if(paramModel.type.indexOf("range") !== -1){
                                        let dArray = paramModel.userSelection.parameterValue.split("-");
                                        if(dArray.length > 0){
                                            paramModel.userSelection.startDate = dArray[0];
                                        }
                                        if(dArray.length > 1){
                                            paramModel.userSelection.endDate = dArray.length > 1?dArray[1]:"";
                                        }
                                    }

                                    // 处理参数类型
                                    processingParamValueByType(paramModel);

                                    paramList.push(paramModel);
                                    break;
                                }
                            }
                        }

                        data.push(paramList);
                    }

                    // 处理关联字段
                    for(let i=0;i<data.length;i++){
                        for(let pIndex=0;pIndex<data[i].length;pIndex++){
                            processingAssociatedFields(data[i][pIndex],data[i]);
                        }
                    }

                    this.dialogVisible_import_data = data;

                }
            }).finally(()=>{
                that.dialogVisible_import_button_status = false;
            });
            event.target.value = "";
        },
        // 提交
        commit(){

            if(this.currentEditSectionIndex !== -1){
                this.$message({message:"请您先保存一下正在编辑的信息！",type: 'error'});
                return;
            }

            var that = this;
            // handleGetTimeData(that,'INPUT_OPEN','endTime',(res)=>{
            //     console.log(res)
            // })
            that.commitButtonIsLoading = true;
            that.$api.infoEntryCommitPost().then(res => {
                if(res.code == 200){
                    that.$message({message: '提交成功！',type: 'success'});
                }
            }).finally(function () {
                that.commitButtonIsLoading = false;
            });
        },
    },
    watch:{
        currentEditSectionIndex(){
            if(this.currentEditSectionIndex === -1){
                this.$store.basicInformation_isSave = true;
            }else{
                this.$store.basicInformation_isSave = false;
            }

        }
    }
}
</script>

<style scoped>

.container{
    position: relative;
    display: flex;
    flex-direction:row;
    align-items: center;
    background: #0000 !important;
    box-shadow: none;
    border-radius: 0px;
    font-size: 14px;
}

.container>.content{
    position: relative;
    width:calc(100% - 190px);
    background-color: #fff;
    box-shadow: 0px 9px 18px 2px rgba(43, 103, 254, 0.05);
    border-radius:6px;
    padding:20px 20px;
    padding-right:30px;
    box-sizing: border-box;
    margin-top: 30px;
}


.groupTitle{
    display: flex;
    padding: 24px 0px;
    padding-right: 17px;
    padding-left: 22px;
}
.groupTitle>.name{
    color: #31478F;
    font-weight: bold;
    margin-right: auto;
}
.groupTitle>.operation{
    margin-right: -35px;
}

/* 数据条 */
.section{
    position: relative;
    padding-top: 28px;
    padding-bottom: 16px;
}
.section:not(:last-child){
    margin-bottom: 10px;
}
.section>.bottomLine{
    height: 1px;
    position: absolute;
    bottom: 0px;
    background-color: rgb(239, 239, 239);
    left: 40px;
    right: 40px;
}
/* 编辑提示 */
.section>.editPrompt{
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: white;
    position:absolute;
    top: 0px;
    bottom: 0px;
    left: 0px;
    right: 0px;
}



/* 侧边操作按钮(编辑、删除) */
.operationButton{
    position:absolute;
    display: flex;
    flex-direction:column;
    align-items: center;
    justify-content: center;
    right:-18px;
    top: 20px;
}
.operationButton>button:first-child{
    margin-bottom: 14px;
}
.operationButton>button:last-child{
    margin: 0px;
}


/* 底部提交按钮 */
.bottomOperation{
    display: flex;
    /* display:none; */
    justify-content: center;

    background: white;
    padding: 21px 0px;
    position: fixed;
    bottom: 0px;
    left: 202px;
    z-index: 1;
    width: calc(100% - 420px);

    box-shadow: -2px -2px 15px 0px rgba(0, 0, 0, 0.2);
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}
.bottomOperation>button{
    margin: 0px 36px;
    font-size: 15px;
    padding: 7px 38px;
}


/* 分页 */
.el-pagination{
    justify-content: flex-end;
    display: flex;
    padding-right: 34px;
}


/* 二级框 - 导入 */
.dialogVisible_import_content{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.dialogVisible_import_content>div{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 20px 0px;
}
.dialogVisible_import_content>div>button{
    margin-bottom: 8px;
}

/* 自定义右侧导航栏位置、尺寸等信息 */
/* .rightSideTab{
    top: 86px;
    bottom:0px;
    right: 24px;
    width: 173px;
} */

</style>
